package cn.ljq.ljq;

import cn.ljq.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MyLjq implements HandlerInterceptor {

    public MyLjq() {
        System.out.println("MyLjq()无惨构造方法...");
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        Object getSession =  request.getSession().getAttribute("DL");  //拿到session的信息

        User user = (User)getSession;  //转型

        String path = request.getServletPath();  //获取请求路径


        if (user != null) {  //如果session不为空

            System.out.println("session不为空");

            if (! user.getRole().equals("adm") && path.startsWith("/adm")) {  //登陆者不是管理员而执行管理员操作

                response.sendRedirect("/public/main");  //返回登录页面

                return false;  //不放行

            } else if (! user.getRole().equals("stu") && path.startsWith("/stu")) {  //登陆者不是学生而执行学生操作

                response.sendRedirect("/public/main");  //返回登录页面

                return false;

            } else if (! user.getRole().equals("tea") && path.startsWith("/tea")) {  //登陆者不是教师而执行教师操作

                response.sendRedirect("/public/main");  //返回登录页面

                return false;

            }

        }else {

            System.out.println("----------------");

            System.out.println("session为空");

            System.out.println("进入拦截器...");

            System.out.println("请求路径 == " + request.getServletPath());

            System.out.println("session == " + request.getSession().getAttribute("DL"));

            System.out.println("================================");

            response.sendRedirect("/public/main");

            return false;

        }
        return true;  //最后放行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
